package com.purchase.util.wxpay.jsapi;

import com.purchase.util.PropertiesUtil;
import com.purchase.util.wxpay.WXPayUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * 验签工具类
 */
public class SignValidUtil {

    private static Logger logger = LoggerFactory.getLogger(SignValidUtil.class);
    private static final String WXPAY_KEY = PropertiesUtil.getValue(PropertiesUtil.WXPATH, "wxpay.key");

    /**
     * 微信验签
     *
     * @param map
     * @throws Exception
     */
    public static void isSignatureValid(Map<String, String> map) throws Exception {

        logger.info("开始验签 {}");
        // 验签
        boolean flag = WXPayUtil.isSignatureValid(map, WXPAY_KEY);
        if (!flag) {
            logger.error("验签失败 {}");
            throw new Exception("验签失败");
        }
        logger.info("验签结束 【验签成功】{}");
    }

    /**
     * 微信验签
     *
     * @param xml
     * @throws Exception
     */
    public static void isSignatureValid(String xml) throws Exception {
        logger.info("开始验签 {}");
        // 验签
        boolean flag = WXPayUtil.isSignatureValid(WXPayUtil.xmlToMap(xml), WXPAY_KEY);
        if (!flag) {
            logger.error("验签失败 {}");
            throw new Exception("验签失败");
        }
        logger.info("验签结束【验签成功】 {}");
    }

    /**
     * 生成签名
     *
     * @param data
     */
    public static String generateSignature(Map<String, String> data) throws Exception {
        logger.info("开始生成签名 {}");
        String sign;
        try {
            sign = WXPayUtil.generateSignature(data, WXPAY_KEY);
            logger.debug("【sign = 】" + sign);
        } catch (Exception e) {
            logger.error("生成签名失败 {}", e);
            throw new Exception("生成签名失败");
        }
        logger.info("生成签名完成 {}");

        return sign;
    }

}
